
"""
Edit the config as a raw text.
"""

import Tkinter as tk
from ScrolledText import ScrolledText

if __name__ == '__main__':
    import os, sys
    os.chdir("..")
    sys.path.insert(0, os.getcwd())

from defaultDialog import DefaultDialog

   

class RawConfigEditDialog(DefaultDialog):
    def __init__(self, parent, cfg):
        self.cfg = cfg
        DefaultDialog.__init__(self, parent)
        
    def setup_widgets(self):
        tk.Label(self, text="Raw config edit (%r):" % self.cfg.filename).pack()

        # Create textfield
        self.textfield = ScrolledText(
            self, width = 79, height = 20
        )
        self.textfield.pack()
        self.textfield.insert(0.0, self.cfg.pformatted())
        
        # Create Buttons
        buttonframe = tk.Frame(self)

        button = tk.Button(buttonframe, text = "validate", command = self.validate)
        button.pack(side=tk.LEFT)
        
        button = tk.Button(buttonframe, text = "save", command = self.save)
        button.pack(side=tk.LEFT)
        
        button = tk.Button(buttonframe, text = "cancel", command = self.cancel)
        button.pack(side=tk.LEFT)
        
        buttonframe.pack(fill=tk.X)
        
        # Create a statusbar
        self.statusbar = tk.Label(self, bd=1, relief=tk.SUNKEN, anchor=tk.W)
        self.statusbar.pack(side=tk.BOTTOM, fill=tk.X)
        self.statusbar.config(text="Config loaded?")
        
        self.textfield.focus_set()
    
    #--------------------------------------------------------------------------
    
    def validate(self, event=None):
        text = self.textfield.get(1.0, tk.END)
        try:
            self.cfg.string_new(text)
        except Exception, err:
            self.statusbar.config(text="Validate Error: %r" % err)
            return
        self.textfield.delete(1.0, tk.END) # Clear the text field
        self.textfield.insert(1.0, self.cfg.pformatted())
        self.statusbar.config(text="Validate, ok.")
    
    def save(self, event=None):
        text = self.textfield.get(1.0, tk.END)
        self.cfg.string_new(text)
        self.cfg.save()
        self.destroy()

    

        

if __name__ == '__main__':
    #test the dialog
    from simpledms import CONFIG_PATH
    from externals.pyconfig.pyconfig import PyConfig
    cfg = PyConfig(filename=CONFIG_PATH, verbose=1, defaults={})
    
    #test the dialog
    root=tk.Tk()
    tk.Label(root, text="Test Tkinter root").pack()
#    tk.Button(
#        root, text='start Dialog', command=lambda:SetupFieldsDialog(root)
#    ).pack()
    RawConfigEditDialog(root, cfg)
#    root.mainloop()